<template>
  <BasicModal v-bind="$attrs" @register="registerDrawer" showFooter :title="getTitle" width="500px" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '@/components/Form';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { FormSchema } from '@/components/Table';
  import { save, update, QuestionCategoryRequest } from '@/api/exam/questionCategory';

  const emit = defineEmits(['success', 'register']);
  const isUpdate = ref(true);
  let record: QuestionCategoryRequest = {};
  const formSchema: FormSchema[] = [
    {
      field: 'category',
      label: '分类名称',
      required: true,
      component: 'Input',
    },
    {
      label: '备注',
      field: 'remark',
      component: 'InputTextArea',
    },
    {
      field: 'status',
      label: '状态',
      component: 'RadioButtonGroup',
      defaultValue: '1',
      componentProps: {
        options: [
          { label: '启用', value: '1' },
          { label: '停用', value: '0' },
        ],
      },
    },
  ];
  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 90,
    baseColProps: { span: 24 },
    schemas: formSchema,
    showActionButtonGroup: false,
  });

  const [registerDrawer, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    console.log('asdfasdfas', data);

    record = unref(data.record);

    if (unref(isUpdate)) {
      setFieldsValue({
        ...data.record,
      });
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增分类' : '编辑分类'));

  async function handleSubmit() {
    try {
      const values: QuestionCategoryRequest = await validate();
      setModalProps({ confirmLoading: true });
      if (isUpdate.value) {
        await update(record.id, values);
      } else {
        await save(values);
      }

      closeModal();
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
